from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger
from app.manage_notice.models.manage_notice_user import ManageNoticeUser

class ManageNoticeUserHandler():
    """  manage notice user Handler
    """
    def __init__(self):
        pass


    def get_notice_user_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配，获取通知人信息
        """
        try:
            field_info = {field: value}
            order_info = {"name": "asc"}
            result = ManageNoticeUser.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.warning(f"get notice user search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get notice user search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result


    def get_notice_user_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配，获取通知人信息
        """
        try:
            result = ManageNoticeUser.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.warning(f"get notice user match, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get notice user match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result


    def add_notice_user(self, db: Session, data: dict):
        """
        创建通知人
        """
        try:
            notice_user_object = ManageNoticeUser.get_object_by_name(db, data["name"])
            if notice_user_object:
                # 如果存在， 则异常返回
                logger.error(f"add notice user failed,{data['name']} was exist")
                return False

            result = ManageNoticeUser.add(db, data)
            if not result:
                logger.error(f"add notice user to database failed")
                return False
        except Exception as e:
            message = f"add notice user error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def update_notice_user(self, db: Session, data: dict):
        """
        修改通知人信息
        """
        try:
            notice_user_object = ManageNoticeUser.get_object_by_uuid(db, data["uuid"])
            if not notice_user_object:
                # 如果不存在， 则异常返回
                logger.error(f"update notice user failed,{data['name']} not exist")
                return False

            result = ManageNoticeUser.update(db, data)
            if not result:
                logger.error(f"update notice user to database failed")
                return False
        except Exception as e:
            message = f"update notice user error "
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def delete_notice_user(self, db: Session, data: dict):
        """
        删除通知人信息
        """
        try:
            notice_user_object = ManageNoticeUser.get_object_by_uuid(db, data['uuid'])
            if not notice_user_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete notice user failed, uuid:{data['uuid']} not exist")
                return False

            # 删除通知人所属的通知组
            notice_user_object.teams = []
            db.commit()

            # 删除通知用户
            ManageNoticeUser.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete notice user uuid:{data['uuid']}  error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True




